<?php

/**
 * alltosun.com 核销平台接口 index.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 高昂 (gaoa@alltosun.com) $
 * $Date: 2015-7-3 上午9:42:33 $
 * $Id$
 */

class Action
{
    private $per_page = 50;

    private $token = '';
    private $user_id = 0;
    private $user_info = array();
    private $api_stat_id = 0;
    private $cardBaseUrl = 'http://yyy.baobaot.com';
    private $getCardDetailUrL = '/index.php?g=Api&m=OpenApi&a=getCardDetail';
    private $cardVerificationUrl = '/index.php?g=Api&m=OpenApi&a=cardVerification';
    private $platform_name = '抱抱堂';

    public function __construct()
    {
        $this->token = an_request('token');

        if ($this->token) {
            $user_info = user_helper::get_user_info_by_token($this->token);
            if ($user_info && $user_info['status'] == 1) {
                $this->user_id = $user_info['id'];
                $this->user_info = $user_info;
            }
        }

        if (ONDEV) {
            $this->cardBaseUrl ='http://wxtest.baobaot.com';
        }
    }

    /**
     * 获取核销平台的展示列表
     */
    public function get_group_platform_list()
    {
        // 验证接口
        $api_stat_id = api_helper::check_sign(array());
        $platform_list = _widget('group_platform')->get_group_platform_list();

        if ($platform_list) {
            api_helper::return_data(0, 'success', $platform_list, $api_stat_id);
        } else {
            api_helper::return_data(1, '暂无核销记录');
        }
    }

    /**
     * 根据核销码查询核销信息
     * @author xiaolin
     * @date   2016-09-30
     * @return json
     */
    public function get_coupon_by_verification_code() {
        $code = an_request('code');

        //数据必填及格式验证
        $this->validation_code($code);

        //加密参数
        $sign_param = array(
            'code' => $code
        );

        //验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        $resdata = $this->get_curl_info_by_code($code);
        $data = array();
        if ($resdata) {
            $data = $this->format_curl_data($resdata);
            $data = array_merge($data, array('code' => $code));
        }

        api_helper::return_data(0, 'success', array('data' => $data), $this->api_stat_id);
    }

    /**
     * 确认核销
     * @author xiaolin
     * @date   2016-09-30
     * @return json
     */
    public function make_verification() {
        $code = an_request('code');
        $store_id = an_request('store_id');

        //数据必填及格式验证
        $this->validation_code($code);

        //加密参数
        $sign_param = array(
            'code' => $code,
            'store_id' => $store_id
        );

        //验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        //获取店铺信息
        $store_info = $this->get_store_info_by_id($store_id);

        $resdata = $this->get_curl_info_by_code($code);
        if ($resdata) {
            //调用接口核销
            $this->card_verification($code);

            $resdata = $this->format_curl_data($resdata);

            //变更抱抱币
            if ($resdata['bbcoin']) {
                bbcoin_helper::change_bbcoin(array(
                    'user_id' => $store_info['user_id'],
                    'res_id' => bbcoin_config::RES_TYPE_VERIFICATION_REWARD,
                    'bbcoin' => $resdata['bbcoin']
                ));
            }

            //记录核销
            _model('verification_record')->create(array_merge(array(
                'user_id' => $store_info['user_id'],
                'code' => $code,
                'add_time' => datetime()
            ), $resdata));
        }

        api_helper::return_data(0, 'success', array(), $this->api_stat_id);
    }

    /**
     * 核销记录总数
     * @author xiaolin
     * @date   2016-10-12
     * @return json
     */
    public function verification_record_count() {
        $store_id = an_request('store_id');

        //加密参数
        $sign_param = array(
            'store_id' => $store_id
        );

        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        $store_info = $this->get_store_info_by_id($store_id);

        //查询条件
        $filter['user_id'] = $store_info['user_id'];
        $count = _model('verification_record')->getTotal($filter);

        api_helper::return_data(0, 'success', array('count' => $count), $this->api_stat_id);
    }

    /**
     * 核销记录列表
     * @author xiaolin
     * @date   2016-09-30
     * @return json
     */
    public function verification_record_list() {
        $page_no = an_request('page_no', 1);
        $store_id = an_request('store_id');

        //加密参数
        $sign_param = array(
            'page_no' => $page_no,
            'store_id' => $store_id
        );

        // 验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        $store_info = $this->get_store_info_by_id($store_id);

        //查询条件
        $filter['user_id'] = $store_info['user_id'];
        $count = _model('verification_record')->getTotal($filter);
        if (!$count) {
            api_helper::return_data(1, '暂无数据');
        }

        //分页配置
        $pager = new Pager($this->per_page);
        $pager->generate($count);
        $page_arr['page_no'] = $page_no;
        $page_arr['pages'] = $pager->getPages();

        $verification_record_list = _model('verification_record')->getList($filter, 'ORDER BY `id` DESC ' . $pager->getLimit($page_no));

        api_helper::return_data(0, 'success', array('verification_record_list' => $verification_record_list, 'pages' => $page_arr), $this->api_stat_id);
    }

    /**
     * 核销记录详情
     * @author xiaolin
     * @date   2016-09-30
     * @return json
     */
    public function verification_record_detail() {
        $id = an_request('id');
        $store_id = an_request('store_id');

        //核销验记录验证
        $this->validation_verification_record($id);

        //加密参数
        $sign_param = array(
            'id' => $id,
            'store_id' => $store_id
        );

        //验证接口
        $this->api_stat_id = api_helper::check_sign($sign_param, 1);

        $store_info = $this->get_store_info_by_id($store_id);

        $res = _uri('verification_record', $id);
        if (!$res) {
            api_helper::return_data(1, '此核销记录不存在');
        }

        if ($res['user_id'] != $store_info['user_id']) {
            api_helper::return_data(1, '该卡券不是该店铺核销的');
        }

        api_helper::return_data(0, 'success', array('verification_record' => $res), $this->api_stat_id);
    }
    
    /**
     * 调用郭维的接口查询核销码对应的内容
     * @author xiaolin
     * @date   2016-10-19
     * @param  string $code 核销码
     * @return json
     */
    private function get_curl_info_by_code($code) {
        $err_msg = null;
        $data = array('cardCode' => $code);
        $param = array(
            'header' => array('Access-Token:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0NzY4NjM4MDcsImV4cCI6MTUwODM5OTgwN30.zlTD2x_8UNh53HGtbPR36NooVv1NwJz9zJa6pzSYleU')
        );
        $res = curl_request($this->cardBaseUrl . $this->getCardDetailUrL, 'post', $data, $err_msg, 20, array(), $param);

        if (!$res) {
            api_helper::return_data(1, '系统异常,请稍后再试');
        }
        $res = json_decode($res, 1);
        if (401 == $res['errcode']) {
            api_helper::return_data(1, 'token校验失败');
        }
        if (1 == $res['errcode']) {
            api_helper::return_data(1, $res['errmsg']);
        }
        if (2 == $res['errcode']) {
            api_helper::return_data(1, '此卡券无效');
        }
        if (0 != $res['errcode']) {
            api_helper::return_data(1, $res['errmsg']);
        }
        if (2 == $res['data']['order_status']) {
            api_helper::return_data(1, '此卡券已核销');
        }
        if (!isset($res['data']) || !$res['data']) {
            api_helper::return_data(1, '未查询到该卡券信息');
        }
        return $res['data'];
    }

    /**
     * 格式化curl过来的数据
     * @author xiaolin
     * @date   2016-10-27
     * @param  array $resdata
     * @return array
     */
    private function format_curl_data($resdata) {
        $use_time = '无限制';
        if ($resdata['card_sdate'] && $resdata['card_edate']) {
            $use_time = $resdata['card_sdate'] . ' - ' . $resdata['card_edate'];
        } elseif ($resdata['card_sdate'] && !$resdata['card_edate']) {
            $use_time = $resdata['card_sdate'] . '之后使用';
        } elseif (!$resdata['card_sdate'] && $resdata['card_edate']) {
            $use_time = $resdata['card_edate'] . '之前使用';
        }

        $use_condition = preg_replace('/<[\/]?p>/i', '', $resdata['user_notice']);
        $use_condition = preg_replace('/<br[ ]?[\/]?>/i', "\n", $use_condition);

        $data = array(
            'platform_name' => $this->platform_name,
            'good_name' => $resdata['card_name'],
            'use_time' => $use_time,
            'use_condition' => $use_condition,
            'bbcoin' => $resdata['worth'] > 0 ? intval($resdata['worth']) : 0,
        );
        return $data;
    }
    /**
     * 调用郭维的接口核销
     * @author xiaolin
     * @date   2016-10-20
     * @param  string $code 核销码
     * @return json
     */
    private function card_verification($code) {
        $err_msg = null;
        $data = array('cardCode' => $code);
        $param = array(
            'header' => array('Access-Token:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0NzY4NjM4MDcsImV4cCI6MTUwODM5OTgwN30.zlTD2x_8UNh53HGtbPR36NooVv1NwJz9zJa6pzSYleU')
        );
        $res = curl_request($this->cardBaseUrl . $this->cardVerificationUrl, 'post', $data, $err_msg, 20, array(), $param);

        if (!$res) {
            api_helper::return_data(1, '系统异常,请稍后再试');
        }
        $res = json_decode($res, 1);
        if (0 !== $res['errcode']) {
            api_helper::return_data(1, $res['errmsg']);
        }
    }

    /**
     * 核销码验证
     * @author xiaolin
     * @date   2016-09-30
     * @param  string $code 核销码
     * @return json
     */
    private function validation_code($code) {
        if (!$code) {
            api_helper::return_data(1, '核销码不能为空');
        }
        if (!preg_match('/^[0-9a-zA-Z]+$/', $code)) {
            api_helper::return_data(1, '核销码格式不正确');
        }
    }

    /**
     * 核销验记录验证
     * @author xiaolin
     * @date   2016-09-30
     * @param  int $id 核销记录ID
     * @return json
     */
    private function validation_verification_record($id) {
        if (!$id) {
            api_helper::return_data(1, '请选择一条核销记录');
        }
    }

    /**
     * 根据店铺id获取店铺信息
     * @author xiaolin
     * @date   2016-10-20
     * @param  int $id 店铺ID
     * @return json || array
     */
    private function get_store_info_by_id($id) {
        if (!$id) {
            api_helper::return_data(1, '请选择一个店铺');
        }

        $store_info = store_helper::get_store($id);
        if (!$store_info || $store_info['status'] == 0) {
            api_helper::return_data(1, '商户不存在或者已删除');
        }

        return $store_info;
    }
}
?>